<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <div id="app" style="border:solid 2px #aaa;width: 300px;padding: 20px;">
        <p v-if="goods.length === 0">全部卖完了</p>
        <ul v-else>
            <li v-for="(item,idx) in goods" :key="item.id">
                {{ item.name }} - {{ item.stock }} - 
                <input type="button" value="-" @click="diff(item.id)" v-if="item.sales">
                {{ item.sales }}
                <input type="button" value="+" @click="add(item.id)" v-if="item.stock !== item.sales">
                <span v-if="item.stock !== item.sales">{{ item.stock - item.sales }}</span>
                <span v-else>卖完了</span>
                <input type="button" value="下架"  @click="del(item.id)">
            </li>
        </ul>
    </div>
</body>
<script src="../vue.global.js"></script>
<script>
    const {createApp} = Vue;

    createApp({
        data(){
            return {
                goods:[{
                    id:1,
                    name:"电脑",
                    stock: 10,
                    sales: 10,
                    price: 2999
                },{
                    id:2,
                    name:"手机",
                    stock: 20,
                    sales: 7,
                    price: 1999
                },{
                    id:3,
                    name:"平板",
                    stock: 15,
                    sales: 10,
                    price: 1566
                }]
            }
        },
        methods:{
            diff(id){
                // 减少购买量，减少销量
                const i = this.indexOf(id);
                this.goods[i].sales--;
            },
            add(id){
                // 增加购买量，增加销量
                const i = this.indexOf(id);
                this.goods[i].sales++;
            },
            del(id){
                // 下架商品，删除数组中的数据
                const i = this.indexOf(id);
                this.goods.splice(i, 1);
            },
            indexOf(id){
                // 根据指定id查询数据在数组中的索引
                let i = 0;
                this.goods.some((val,idx)=>{
                    i = idx;
                    return val.id === id;
                })
                return i;
            }
        }
    }).mount("#app");

</script>
</html>